#include <iostream>
#include "UserManager.h"
#include "DeviceManager.h"
#include "LogManager.h"
#include "ConfigManager.h"
#include "DatabaseManager.h"
#include "ExceptionHandler.h"
#include "ThreadPool.h"

using namespace std;

// 初始化系统
void initializeSystem() {
    // 初始化配置管理器
    //ConfigManager& configManager = ConfigManager::getInstance();
    //cout << "Database path: " << configManager.getConfig("database_path") << endl;
    //cout << "Log level: " << configManager.getConfig("log_level") << endl;

    // 初始化数据库管理器
    DatabaseManager& dbManager = DatabaseManager::getInstance();
    dbManager.executeQuery("CREATE TABLE IF NOT EXISTS users (id INT PRIMARY KEY, username TEXT, password_hash TEXT, role TEXT);");
    dbManager.executeQuery("CREATE TABLE IF NOT EXISTS devices (id INT PRIMARY KEY, device_type TEXT, status TEXT, last_modified TIMESTAMP);");
    dbManager.executeQuery("CREATE TABLE IF NOT EXISTS logs (id INT PRIMARY KEY, log_type TEXT, timestamp TIMESTAMP, user_id INT, device_id INT, log_content TEXT);");

    // 初始化设备管理器
    //DeviceManager& deviceManager = DeviceManager::getInstance();
    //deviceManager.addDevice(Device(1, Device::DeviceType::LIGHT));
    //deviceManager.addDevice(Device(2, Device::DeviceType::THERMOSTAT));

    // 初始化用户管理器
    //UserManager& userManager = UserManager::getInstance();
    //userManager.registerUser("admin", "admin123");
    //userManager.registerUser("user", "user123");

    // 初始化日志管理器
    LogManager& logManager = LogManager::getInstance();
    logManager.logAction(Log::LogType::INFO, 1, 1, "系统初始化");
}

// 用户注册
void registerUser() {
    UserManager& userManager = UserManager::getInstance();
    LogManager& logManager = LogManager::getInstance();

    string username, password;
    cout << "请输入用户名: ";
    cin >> username;
    cout << "请输入密码: ";
    cin >> password;

    bool success = userManager.registerUser(username, password,User::Role::DEFAULT);
    if (success) {
        cout << "用户注册成功." << endl;
        logManager.logAction(Log::LogType::INFO, -1, -1, "新用户注册: " + username);
    } else {
        cerr << "错误:用户注册失败(用户名可能已存在) << endl";
    }

}

void manageDevices(int userId) {
    DeviceManager& deviceManager = DeviceManager::getInstance();
    LogManager& logManager = LogManager::getInstance();

    while (true) {
        cout << "\n===== 设备管理 =====" << endl;
        cout << "1. 添加设备" << endl;
        cout << "2. 删除设备" << endl;
        cout << "3. 控制设备" << endl;
        cout << "4. 批量启用设备" << endl;
        cout << "5. 批量禁用设备" << endl;
        cout << "6. 返回上一级" << endl;
        cout << "请输入您的选择: ";

        int choice;
        cin >> choice;

        if (choice == 1) {
            // 添加设备
            int deviceId;
            string deviceTypeStr;
            cout << "请输入设备ID: ";
            cin >> deviceId;
            cout << "请输入设备类型 (LIGHT, THERMOSTAT, CAMERA, SOCKET): ";
            cin >> deviceTypeStr;

            Device::DeviceType type = Device::DeviceType::DEFAULT;
            if (deviceTypeStr == "LIGHT") type = Device::DeviceType::LIGHT;
            else if (deviceTypeStr == "THERMOSTAT") type = Device::DeviceType::THERMOSTAT;
            else if (deviceTypeStr == "CAMERA") type = Device::DeviceType::CAMERA;
            else if (deviceTypeStr == "SOCKET") type = Device::DeviceType::SOCKET;

            Device* device = DeviceFactory::createDevice(type, deviceId);
            if (device) {
                deviceManager.addDevice(*device);
                logManager.logAction(Log::LogType::INFO, userId, deviceId, "添加设备: " + to_string(deviceId));
            }
        } else if (choice == 2) {
            // 删除设备
            int deviceId;
            cout << "请输入设备ID: ";
            cin >> deviceId;
            deviceManager.removeDevice(deviceId);
            logManager.logAction(Log::LogType::INFO, userId, deviceId, "删除设备: " + to_string(deviceId));
        } else if (choice == 3) {
            // 控制设备
            int deviceId;
            string newStatus;
            cout << "请输入设备ID: ";
            cin >> deviceId;
            cout << "请输入更新状态 (on/off): ";
            cin >> newStatus;

            Device* device = deviceManager.getDevice(deviceId);
            if (device) {
                deviceManager.updateDeviceStatus(deviceId, newStatus);
                logManager.logAction(Log::LogType::INFO, userId, deviceId, "设备状态更新为 " + newStatus);
                cout << "设备状态更新成功" << endl;
            } else {
                cerr << "错误:设备未找到" << endl;
            }
        } else if (choice == 4) {
            // 批量启用设备
            vector<int> deviceIds;
            int deviceId;
            cout << "请输入设备ID（输入-1结束）: ";
            while (cin >> deviceId && deviceId != -1) {
                deviceIds.push_back(deviceId);
            }
            deviceManager.batchEnableDevices(deviceIds);
            logManager.logAction(Log::LogType::INFO, userId, -1, "批量启用设备");
        } else if (choice == 5) {
            // 批量禁用设备
            vector<int> deviceIds;
            int deviceId;
            cout << "请输入设备ID（输入-1结束）: ";
            while (cin >> deviceId && deviceId != -1) {
                deviceIds.push_back(deviceId);
            }
            deviceManager.batchDisableDevices(deviceIds);
            logManager.logAction(Log::LogType::INFO, userId, -1, "批量禁用设备");
        } else if (choice == 6) {
            // 返回上一级
            break;
        } else {
            cerr << "无效的选择，请重新输入" << endl;
        }
    }
}

// 检查日志
void checkLogs(int userId) {
    LogManager& logManager = LogManager::getInstance();

    cout << "===== Logs =====" << endl;
    vector<Log> logs = logManager.getLogsByUser(userId);
    for (const auto& log : logs) {
        cout << "日志类型: " << static_cast<int>(log.getLogType())
             << ", 用户 ID: " << log.getUserId()
             << ", 设备 ID: " << log.getDeviceId()
             << ", 内容: " << log.getContent() << endl;
    }
    // 在实际操作完成后更新活动时间
    UserManager::getInstance().updateActivityTime(userId);
}

// 管理用户（仅管理员可用）
void manageUsers() {
    UserManager& userManager = UserManager::getInstance();
    LogManager& logManager = LogManager::getInstance();

    cout << "===== 用户管理 =====" << endl;
    cout << "1. 添加用户" << endl;
    cout << "2. 删除用户" << endl;
    cout << "3. 修改用户角色" << endl;
    cout << "请输入您的选择: ";

    int choice;
    cin >> choice;

    if (choice == 1) {
        string username, password;
        cout << "请输入用户名: ";
        cin >> username;
        cout << "请输入密码: ";
        cin >> password;
        if (userManager.addUser(username, password, User::Role::DEFAULT)) {
            logManager.logAction(Log::LogType::INFO, -1, -1, "添加用户: " + username);
        }
    } else if (choice == 2) {
        int userId;
        cout << "请输入用户ID: ";
        cin >> userId;
        if (userManager.deleteUser(userId)) {
            logManager.logAction(Log::LogType::INFO, -1, -1, "删除用户: " + to_string(userId));
        }
    } else if (choice == 3) {
        int userId;
        User::Role newRole;
        cout << "请输入用户ID: ";
        cin >> userId;
        cout << "请输入新角色 (0: 普通用户, 1: 管理员): ";
        int roleInput;
        cin >> roleInput;
        newRole = static_cast<User::Role>(roleInput);
        if (userManager.updateUserRole(userId, newRole)) {
            logManager.logAction(Log::LogType::INFO, -1, -1, "修改用户角色: " + to_string(userId) + " -> " + to_string(static_cast<int>(newRole)));
        }
    } else {
        cerr << "无效的选择，请重新输入" << endl;
    }


}


// 显示操作页面
void showOperationPage() {
    UserManager& userManager = UserManager::getInstance();
    //DeviceManager& deviceManager = DeviceManager::getInstance();
    LogManager& logManager = LogManager::getInstance();

    int userId = -1; // 当前登录用户的ID
    string username;

    while (true) {
        // 清理过期会话
        userManager.cleanExpiredSessions();

        // 检查当前用户的会话是否过期
        if (userId != -1 && userManager.isSessionExpired(userId)) {
            cout << "会话已过期，请重新登录。" << endl;
            userId = -1; // 重置用户ID
        }

        cout << "\n===== 智能家居系统 =====" << endl;

        cout << "islocked? = " << userManager.isSystemLocked() << endl;
        // 检查系统是否被锁定
        //if (userManager.isSystemLocked()) {
        //    cout << "系统已被锁定，请稍后再试。" << endl;
        //    continue; 
        //}
        
        if (userId == -1) {
            cout << "1. 登录" << endl;
            cout << "2. 注册" << endl; // 新增注册选项
            cout << "3. 退出系统" << endl;
        } else {
            User* user = userManager.getUser(userId);
            if (user && user->getRole() == User::Role::ADMIN) {
                cout << "1. 控制设备" << endl;
                cout << "2. 检查日志" << endl;
                cout << "3. 管理用户" << endl;
                cout << "4. 登出" << endl;
            } else {
                cout << "1. 控制设备" << endl;
                cout << "2. 检查日志" << endl;
                cout << "3. 登出" << endl;
            }
        }
        cout << "请输入您的选择: ";

        int choice;
        cin >> choice;

        if (userId == -1) {
            // 未登录状态
            if (choice == 1) {
                // 先检查系统是否被锁定
                if (userManager.isSystemLocked()) {
                    cout << "系统已被锁定，请稍后再试。" << endl;
                    continue; // 直接跳过后续输入步骤
                }
                // 系统未锁定，才进行登录操作
                string password;
                cout << "输入用户名: ";
                cin >> username;
                cout << "输入密码: ";
                cin >> password;

                if (userManager.loginUser(username, password)) {
                    User* user = userManager.getUserByUsername(username);
                    if (user) {
                        userId = user->getId();
                        logManager.logAction(Log::LogType::INFO, userId, -1, "User logged in.");
                        cout << "登录成功, 欢迎回来 " << username << "!" << endl;
                        cout << "用户角色: " << (user->getRole() == User::Role::ADMIN ? "管理员" : "普通用户") << endl;
					} else {
                        cerr << "错误:用户名未找到" << endl;
                    }
                } else {
                    cerr << "登录失败，无效的用户名或密码" << endl;
                }
            } else if (choice == 2) {
                // 调用注册功能
                registerUser();
            } else if (choice == 3) {
                cout << "退出系统。。。" << endl;
                break;
            } else {
                cerr << "无效的选择，请重新输入" << endl;
            }
        } else {
            // 已登录状态
	    // userManager.updateActivityTime(userId); // 更新最后活动时间

            User* user = userManager.getUser(userId);
            if (user && user->getRole() == User::Role::ADMIN) {
                // 管理员菜单
                if (choice == 1) {
                    manageDevices(userId);
                } else if (choice == 2) {
                    checkLogs(userId);
                } else if (choice == 3) {
                    manageUsers();
                } else if (choice == 4) {
                    userManager.logoutUser(userId);
                    logManager.logAction(Log::LogType::INFO, userId, -1, "User logged out.");
                    cout << "登出成功,再见 " << username << "!" << endl;
                    userId = -1; // 重置用户ID
                } else {
                    cerr << "无效的选择，请重新输入" << endl;
                }
            } else {
                // 普通用户菜单
                if (choice == 1) {
                    manageDevices(userId);
                } else if (choice == 2) {
                    checkLogs(userId);
                } else if (choice == 3) {
                    userManager.logoutUser(userId);
                    logManager.logAction(Log::LogType::INFO, userId, -1, "User logged out.");
                    cout << "登出成功,再见 " << username << "!" << endl;
                    userId = -1; // 重置用户ID
                } else {
                    cerr << "无效的选择，请重新输入" << endl;
                }
            }
        }
    }
}

int main() {
    try {
        // 初始化系统
        initializeSystem();

        // 显示操作页面
        showOperationPage();

        // 保存日志到文件
        LogManager::getInstance().saveLogsToFile("system_logs.txt");

    } catch (const exception& e) {
        ExceptionHandler::handleException(e);
        ExceptionHandler::logException(e);
    }

    return 0;
}
